package com.asiainfo.ncrm;


import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;




import java.util.Date;
import java.util.HashMap;
import java.util.Map;

















import net.sf.json.JSONObject;

import com.asiainfo.ncrm.base.BaseHttp;
import com.asiainfo.ncrm.base.HttpCallBack;
import com.asiainfo.ncrm.base.Result;
import com.asiainfo.ncrm.bean.UserInfo;
import com.asiainfo.ncrm.common.Constant;
import com.asiainfo.ncrm.dialog.DialogWidget;
import com.asiainfo.ncrm.update.DialogHelper;
import com.asiainfo.ncrm.update.UpdateManager;
import com.asiainfo.ncrm.util.CustomProgressDialog;
import com.asiainfo.ncrm.util.HttpConstant;
import com.asiainfo.ncrm.util.MD5Helper;
import com.asiainfo.ncrm.util.X;
import com.asiainfo.ncrm.util.XUtils;
import com.asiainfo.ncrm.view.OnPasswordInputFinish;
import com.asiainfo.ncrm.view.PasswordView;
import com.asiainfo.ncrm.view.SwitchView;
import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.text.InputFilter;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private EditText textname = null;
	private EditText pwd = null;
	private Button login = null;
	private TextView version=null;
	private SwitchView switchView;

	private Handler mHandler = new Handler();
	private Handler printHandler = new Handler();
	private ProgressDialog progressDialog;
	private ProgressDialog updateProgressDialog;
	private String resultStr="请重新调整拍照角度以及光线";
	WebView webview;
	private WindowManager wm = null;
	private JSONObject resultObj;
	private String param;
	private UpdateManager updateMan;
	private boolean isOut = false;
	private boolean isIn = false;
	private boolean ssoLogin = false;
	private String userno = "";
	private String password = "";
	private String staffNumber = "";
	private String olNbr = "";
	private String sign = "";
	private String sysCode = "";
	private String data = "";
	private TelephonyManager tm = null;
	private BluetoothAdapter adapter = null;
	private ValueCallback<Uri> mUploadMessage; // 上传文件时用
	private Context mContext;

	protected BaseHttp bh ;

	private String linkPhone;

	private CustomProgressDialog customDialog;

	private DialogWidget mDialogWidget;

    private String checkSMScode= "";


	private boolean result = true;

	private int time = 60;
	private int count = 0;

	private Thread thread;

	private boolean LoginMode=false;//短信登录方式


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_2);

		textname=  (EditText) this.findViewById(R.id.login_text);

		pwd = (EditText)this.findViewById(R.id.login_pwd);
		mContext= this;
		login = (Button) this.findViewById(R.id.tologin);
		bh= new BaseHttp(this);

		switchView= (SwitchView)this.findViewById(R.id.switchPhone);
		switchView.toggleSwitch(false);//初始化为false
		switchView.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
			@Override
			public void toggleToOn(SwitchView view) {
				view.toggleSwitch(true); // or false
				textname.setHint("请输入手机号");
				textname.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
				textname.setText("");
				pwd.setText("");
				findViewById(R.id.pwdlayout).setVisibility(View.INVISIBLE);
				LoginMode=true;
			}

			@Override
			public void toggleToOff(SwitchView view) {
				view.toggleSwitch(false); // or true
				textname.setHint(R.string.login_hint_phone);
				textname.setFilters(new InputFilter[]{});
				textname.setText("");
				pwd.setText("");
				findViewById(R.id.pwdlayout).setVisibility(View.VISIBLE);
				LoginMode=false;
			}
		});

		version = (TextView) this.findViewById(R.id.version);
		String pkName = this.getPackageName();
		try {
			version.setText("当前版本:"+this.getPackageManager().getPackageInfo(pkName, 0).versionName.toString());
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}


		login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if(LoginMode){//短信登录方式
					String staffcode = textname.getText().toString();
					if ((staffcode == null || "".equals(staffcode)) ) {
						Toast.makeText(mContext, "手机号为空", Toast.LENGTH_LONG).show();
						return;
					}
					if(!XUtils.isPhone(staffcode)){
						Toast.makeText(mContext, "手机号不符合规范", Toast.LENGTH_LONG).show();
						return;
					}

					//调用http协议
					String path = Constant.OUTURL + "/BizHall/superSo/loginByAndroid";
					try {

						/*封装Person数组*/
						/*把JSON数据转换成String类型使用输出流向服务器写*/
						String content = "{staffCode:" + URLEncoder.encode(staffcode, "utf-8")+"}";

						Map<String, Object> mymap = new HashMap<String, Object>();
						mymap.put("staffCode", URLEncoder.encode(staffcode, "utf-8"));

						userno = URLEncoder.encode(staffcode, "utf-8");

						path = path + "?linkPhone=" + URLEncoder.encode(staffcode, "utf-8") +  "&" + (new Date()).getTime();

						bh.post(path, null, new TypeToken<Result<UserInfo>>() {
						});

						bh.callBack(new HttpCallBack() {

							@Override
							public <T> void onSuccess(String msg, T result) {
								// TODO 自动生成的方法存根
								//保存用户名密码
//								saveLoginInfo(mContext, userno, password);

								UserInfo user = (UserInfo) result;

									linkPhone = user.getLINK_TELE_NUMBER();

									Toast.makeText(mContext, "请输入短信验证码", Toast.LENGTH_LONG).show();

									checkSMScode = user.getMd5Pwd();

									takeMsg(linkPhone);

							}

							@Override
							public <T> void onFailure(String msg, T result) {
								// TODO 自动生成的方法存根
								Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
							}

						});
					} catch (Exception e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}


				}else {

					String staffcode = textname.getText().toString();
					String codepwd = pwd.getText().toString();

					if ((staffcode == null || "".equals(staffcode)) || (codepwd == null || "".equals(codepwd))) {
						Toast.makeText(mContext, "账户密码为空", Toast.LENGTH_LONG).show();
						return;
					}
					//调用http协议
					String path = Constant.OUTURL + "/BizHall/superSo/loginByAndroid";
					try {

						/*封装Person数组*/
						/*把JSON数据转换成String类型使用输出流向服务器写*/
						String content = "{staffCode:" + URLEncoder.encode(staffcode, "utf-8") + ",password:" + URLEncoder.encode(codepwd, "utf-8") + "}";

						Map<String, Object> mymap = new HashMap<String, Object>();
						mymap.put("staffCode", URLEncoder.encode(staffcode, "utf-8"));
						mymap.put("password", URLEncoder.encode(codepwd, "utf-8"));

						userno = URLEncoder.encode(staffcode, "utf-8");
						password = URLEncoder.encode(codepwd, "utf-8");

						path = path + "?staffCode=" + URLEncoder.encode(staffcode, "utf-8") + "&password=" + URLEncoder.encode(codepwd, "utf-8") + "&" + (new Date()).getTime();

						bh.post(path, null, new TypeToken<Result<UserInfo>>() {
						});

						bh.callBack(new HttpCallBack() {

							@Override
							public <T> void onSuccess(String msg, T result) {
								// TODO 自动生成的方法存根
								//保存用户名密码
								saveLoginInfo(mContext, userno, password);

								UserInfo user = (UserInfo) result;

								linkPhone = user.getLINK_TELE_NUMBER();

								if (user.getSMS() != null && !"".equals(user.getSMS())) {//存在跳过短信验证的权限

									if (!user.getSTAFF_CODE().equals("")) {
										Intent i = new Intent();
										i.putExtra("staffCode", userno);
										i.putExtra("password", password);
										i.setClass(mContext, HomeActivity.class);
										mContext.startActivity(i);
										stopTime();
									}

									Toast.makeText(mContext, "登录成功", Toast.LENGTH_LONG).show();
								} else {
									Toast.makeText(mContext, "请输入短信验证码", Toast.LENGTH_LONG).show();

									checkSMScode = user.getMd5Pwd();

									takeMsg(linkPhone);

								}


							}

							@Override
							public <T> void onFailure(String msg, T result) {
								// TODO 自动生成的方法存根
								Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
							}

						});
					} catch (Exception e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
				}
			}
		});

		mContext=this;
		// 清理webview cookies缓存
		clearCookies();
		super.onCreate(savedInstanceState);
		tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

		SharedPreferences sharedPre=getSharedPreferences("config", MODE_PRIVATE);
        String username=sharedPre.getString("username", "");
        String password= sharedPre.getString("password", "");

        if(username != null && !"".equals(username)){
        	textname.setText(username);
        }
		if(username != null && !"".equals(username)){
			pwd.setText(password);
		}

		// 不显示状态栏
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 加载页面
		// 根据内网网地址判断该载入内网或者外网
//		checkUrlAndLoadView();
		Intent i=getIntent();
		linkPhone = i.getStringExtra("linkPhone");
	 if(linkPhone != null && !"".equals(linkPhone)){
		 String path=Constant.OUTURL+"/BizHall/superSo/loginByAndroid?linkPhone="+linkPhone;

		 loginPoint(path);

		}

		// 检查是否有更新
		updateMan = new UpdateManager(MainActivity.this, appUpdateCb);
		updateMan.checkUpdate();
		adapter = BluetoothAdapter.getDefaultAdapter();
	}

	/**
	 * 短信登录方式
	 */
	public void takeMsg(String phone){
		linkPhone=phone;
		final PasswordView pwdView = new PasswordView(mContext);

		mDialogWidget=new DialogWidget(MainActivity.this, pwdView );

		pwdView.setOnFinishInput(new OnPasswordInputFinish() {
			@Override
			public void inputFinish() {
				if( pwdView.getStrPassword().equals(checkSMScode)){//加入验证成功
					stopTime();
					Intent i = new Intent();
					if(LoginMode){
						i.putExtra("linkPhone", userno);
					}else {
						i.putExtra("staffCode", userno);
						i.putExtra("password", password);
					}
					i.setClass(mContext, HomeActivity.class);
					mContext.startActivity(i);

					mDialogWidget.dismiss();

					Toast.makeText(mContext, "登录成功", Toast.LENGTH_LONG).show();

				}else{
					Toast.makeText(mContext, "您输入的短信验证码不正确，请重新输入", Toast.LENGTH_LONG).show();
				}

			}



		});

		pwdView.getCancelImageView().setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
//                                        Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
				stopTime();
				mDialogWidget.dismiss();

			}
		});
		//重新发送短信方法
		pwdView.getForgetTextView().setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v) {
				try {

					String receiver = linkPhone;
					if(receiver == "" ){

						Toast.makeText(mContext, "获取验证码失败,请重新输入账户密码", Toast.LENGTH_LONG).show();
						mDialogWidget.dismiss();

						return;
					}
					Map<String,Object> mymap = new HashMap<String, Object>();
//											String path=Constant.OUTURL+"/BizHall/custQuery/sendMsgCheckNum";
//											path += "?jsonStr={\"userNo\":20985,\"sender\":\"CRM\",\"receiver\":\""+receiver+"\",\"routeParam\":{\"areaId\":10104}}";
					String staffcode= textname.getText().toString();
					String codepwd = pwd.getText().toString();
					String path = Constant.OUTURL + "/BizHall/superSo/loginByAndroid";
					if(LoginMode) {

						path = path + "?linkPhone=" + URLEncoder.encode(staffcode, "utf-8") + "&" + (new Date()).getTime();
					}else{
						path = path + "?staffCode=" + URLEncoder.encode(staffcode, "utf-8") + "&password=" + URLEncoder.encode(codepwd, "utf-8") + "&" + (new Date()).getTime();

					}

					bh.post(path,null, new TypeToken<Result<UserInfo>>() {
					});

					bh.callBack(new HttpCallBack() {

						@Override
						public <T> void onSuccess(String msg, T result) {
							UserInfo user = (UserInfo) result;

							showTime(pwdView.getForgetTextView());
							Toast.makeText(mContext, "发送短信成功", Toast.LENGTH_LONG).show();

							checkSMScode= user.getMd5Pwd();//保存验证码


						}

						@Override
						public <T> void onFailure(String msg, T result) {
							// TODO 自动生成的方法存根
							Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
						}

					});
				} catch (Exception e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
		});
		String tempPhone_head = linkPhone.substring(0,3);
		String tempPhone_end= linkPhone.substring(7,linkPhone.length());
		pwdView.getPay_title().setText("已发送短信至"+tempPhone_head+"****"+tempPhone_end);


		mDialogWidget.show();

		showTime(pwdView.getForgetTextView());
	}


	/**
	 * 单点登录
	 */
	 public void loginPoint(String path){
		 bh.post(path,null, new TypeToken<Result<UserInfo>>() {
			});

			bh.callBack(new HttpCallBack() {

				@Override
				public <T> void onSuccess(String msg, T result) {
					// TODO 自动生成的方法存根

					UserInfo user = (UserInfo) result;
					if(!user.getSTAFFNAME().equals("")){
						Intent i = new Intent();
						i.putExtra("linkPhone",linkPhone );
		            	i.setClass(mContext, HomeActivity.class);
		            	mContext.startActivity(i);
		            	Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_LONG).show();
					}else{
						Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_LONG).show();
					}



				}

				@Override
				public <T> void onFailure(String msg, T result) {
					// TODO 自动生成的方法存根
					Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_LONG).show();
				}

			});
	 }

	//短信发送变黑
	/**
	 * 显示时间在梯减的文本框
	 */
	public void showTime(final TextView sendSms) {
		thread =new Thread(new Runnable() {
			@Override
			public void run() {
				while (result) {
					time--;
					try {
						Thread.sleep(1000);
//                                     tvShowTime.setText(time + "s后从新获取");
						sendSms.post(new Runnable() {
							@Override
							public void run() {
								sendSms.setText(time + "s后重新获取");
								sendSms.setClickable(false);
								sendSms.setTextColor(Color.rgb(204, 204, 204));
//                                btGetVerificationCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.text_layout_bg_codenotedit));
							}
						});
						if (time <= 1) {
							count=0;
							result = false;
							sendSms.post(new Runnable() {
								@Override
								public void run() {
									sendSms.setText("再次发送");
									sendSms.setClickable(true);
									sendSms.setTextColor(Color.rgb(44, 193, 84));
//                                    btGetVerificationCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.selector_btn_red));
								}
							});
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				result = true;
				time = 60;
			}
		});

		thread.start();
	}

	public void stopTime(){
		result= false;
		time=60;
	}


	/**
     * 使用SharedPreferences保存用户登录信息
     * @param context
     * @param username
     * @param password
     */
    public static void saveLoginInfo(Context context,String username,String password){
        //获取SharedPreferences对象
        SharedPreferences sharedPre=context.getSharedPreferences("config", context.MODE_PRIVATE);
        //获取Editor对象
        Editor editor=sharedPre.edit();
        //设置参数
        editor.putString("username", username);
        editor.putString("password", password);
        //提交
        editor.commit();
    }

    public void onBackPressed() {
    	super.onBackPressed();
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void tologin(){
		//��ʼloadding


//		bh.post(HttpConstant.URL_LOGIN, Params.getLogin(mobile, code), NEW TYPETOKEN<RESULT<USERINFO>>() {
//		});
	}

	private void clearCookies() {
		CookieSyncManager.createInstance(this);
		CookieSyncManager.getInstance().startSync();
		String CookieStr = CookieManager.getInstance().getCookie(
				Constant.OUTURL);
		Log.i("系统输出", "CookieStr=" + CookieStr); // 设置数据库缓存路径
		CookieManager.getInstance().removeSessionCookie();
	}


	// 自动更新回调函数
    UpdateManager.UpdateCallback appUpdateCb = new UpdateManager.UpdateCallback()
    {

        public void downloadProgressChanged(int progress) {
            if (updateProgressDialog != null
                    && updateProgressDialog.isShowing()) {
                updateProgressDialog.setProgress(progress);
            }

        }

        public void downloadCompleted(Boolean sucess, CharSequence errorMsg) {
            if (updateProgressDialog != null
                    && updateProgressDialog.isShowing()) {
                updateProgressDialog.dismiss();
            }
            if (sucess) {
                updateMan.update();
            } else {
                DialogHelper.Confirm(MainActivity.this,
                        R.string.dialog_error_title,
                        R.string.dialog_downfailed_msg,
                        R.string.dialog_downfailed_btnnext,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int which) {
                                updateMan.downloadPackage();
                            }
                        }, R.string.dialog_downfailed_btnnext, null);
            }
        }

        public void downloadCanceled()
        {
            // TODO Auto-generated method stub

        }



        public void checkUpdateCompleted(Boolean hasUpdate,
                CharSequence updateInfo) {
            if (hasUpdate) {
                DialogHelper.Confirm(MainActivity.this,
                        getText(R.string.dialog_update_title),
                        getText(R.string.dialog_update_msg).toString()
                        +updateInfo,
                                getText(R.string.dialog_update_btnupdate),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                updateProgressDialog = new ProgressDialog(MainActivity.this);
                                updateProgressDialog.setMessage(getText(R.string.dialog_downloading_msg));
                                updateProgressDialog.setIndeterminate(false);
                                updateProgressDialog .setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                updateProgressDialog.setMax(100);
                                updateProgressDialog.setProgress(0);
                                updateProgressDialog.show();
                                updateMan.downloadPackage();
                            }
                        },getText( R.string.dialog_update_btnnext), null);
            }
        }
    };
    private void startProgressDialog(){
		if (customDialog == null){
			customDialog = CustomProgressDialog.createDialog(mContext);
			customDialog.setMessage("正在登陆中.......");
		}

		customDialog.show();
	}

	private void stopProgressDialog(){
		if (customDialog != null){
			customDialog.dismiss();
			customDialog = null;
		}
	}


}
